package sampleguiplugin;

import gamefw.framework.Coordinate;
import gamefw.uiplugin.IOutputManager;
import gamefw.uiplugin.IVisualResource;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.ArrayList;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class SampleGUIOutputManager extends JPanel implements IOutputManager {
	
	/**
	 * Auto generated
	 */
	private static final long serialVersionUID = -1207324958843715245L;
	
	private JFrame mainFrame;
	
	private class DrawElement {
		public DrawElement(BufferedImage image, Coordinate offset) {
			this.image = image;
			this.offset = offset;
		}
		
		public BufferedImage image;
		public Coordinate offset;
	}
	
	private ArrayList<DrawElement> drawElements;
	
	public SampleGUIOutputManager(JFrame mainFrame) {
		this.mainFrame = mainFrame;
		
		setPreferredSize(mainFrame.getContentPane().getPreferredSize());
		this.mainFrame.setContentPane(this);
		this.mainFrame.pack();
		this.mainFrame.setResizable(false);
	}

	@Override
	public void beginDraw() {
		this.drawElements = new ArrayList<DrawElement>();
	}

	@Override
	public void endDraw() {
		this.mainFrame.getContentPane().repaint();
	}

	@Override
	public void draw(Coordinate offset, IVisualResource visualResource) {
		if (!(visualResource instanceof SampleGUIVisualResource)) {
			return;
		}
		
		SampleGUIVisualResource resource = (SampleGUIVisualResource)visualResource;
		BufferedImage image = resource.getImage();
		
		if (image != null) {
			this.drawElements.add(new DrawElement(image, offset));
		}
	}
	
	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		
		if (this.drawElements != null) {
			for (DrawElement element : this.drawElements) {
				g.drawImage(
						element.image,
						element.offset.getX(),
						element.offset.getY(),
						element.image.getWidth(),
						element.image.getHeight(),
						null);
			}
		}
	}

	@Override
	public void printString(String message) {
		JOptionPane.showMessageDialog(this.mainFrame, message);
	}
}
